import { createRouter, createWebHistory } from 'vue-router';
import { useAuthStore } from '@/stores/auth';

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/components/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/components/Register.vue')
  },
  {
    path: '/todo',
    name: 'TodoList',
    component: () => import('@/components/TodoList.vue'),
    meta: { requiresAuth: true } // 需要认证才能访问
  },
  {
    path: '/',
    redirect: '/todo'
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 全局前置守卫：验证登录状态
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore();

  // 初始化认证状态（从本地存储读取）
  authStore.initAuth();

  // 检查路由是否需要认证
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next('/login'); // 未登录则重定向到登录页
  } else {
    next(); // 允许访问
  }
});

export default router;